package com.cml.springcloud.loadbalancer.impl;

import com.cml.springcloud.loadbalancer.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author cml
 * @create 2021/4/19 10:28
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    @Override
    public ServiceInstance getInstance(List<ServiceInstance> instances) {
        int index = getAndIncrement() % instances.size();
        return instances.get(index);
    }

    public final int getAndIncrement(){
        int current;
        int next;
        do{
            if(this.atomicInteger.get()>=Integer.MAX_VALUE){
                this.atomicInteger.set(0);
            }
            current = this.atomicInteger.get();
            next = current+1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        return next;
    }
}
